/*
 * @Description: 
 * @Author: lgt
 * @Date: 2021-06-27 13:46:29
 * @LastEditTime: 2021-07-10 08:24:05
 * @LastEditors: xxx
 */
const bcrypt = require('bcryptjs'); //密码加密包
const {Sequelize,Model} = require("sequelize");
const {sequelize} = require("../../core/db");
// const 

class User extends Model {
    static async verifyEmailPassword(email,plainPassword){
        const user = await User.findOne({
            where: {
                email
            }
        })

        if (!user) {
            throw new global.errs.AuthFailed('账号不存在')
        }

        // 验证密码
        const correct = bcrypt.compareSync(plainPassword, user.password)

        if (!correct) {
            throw new global.errs.AuthFailed('密码不正确')
        }

        return user
       
    }
    // 查询是否存在 openid 的小程序用户
    static async getUserByOpenid(openid){
        //查询用户
        const user = await User.findOne({
            where:{
                openid
            }
        })

        return user;
    }

    // 注册小程用户
    static async createUserByOpenid(openid) {
        // 查询用户
        const user = await User.create({
            openid
        })

        return user;
    }

}

User.init({
    id:{
        type:Sequelize.INTEGER,
        primaryKey:true,//设置为主键 不能重复，不能为空
        autoIncrement:true,//自增
    },
    nickname: Sequelize.STRING,
    email:{
        type: Sequelize.STRING(128),
        unique: true
    },
    password: {
        // 扩展 设计模式 观察者模式
        // ES6 Reflect Vue3.0
        type: Sequelize.STRING,
        set(val) {
            // 加密
            const salt = bcrypt.genSaltSync(10)
            // 生成加密密码
            const psw = bcrypt.hashSync(val, salt)
            this.setDataValue("password", psw)
        }
    },
    openid:{
        type:Sequelize.STRING(64),
        unique:true
    }
},{sequelize,tableName: 'user'})

module.exports = {
    User
}
